<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Iwanli\Wxxcx\Wxxcx;
use Yansongda\Pay\Pay;
use App\Models\Notify;
class WxController extends Controller
{
    public $config = [] ;
    public function __construct()
    {
        $this->config = [
            'appid'         => config("wechat.appid"), // APP APPID
            'app_id'        => config("wechat.app_id"), // 公众号 APPID
            'secret'        => config("wechat.secret"),
            'miniapp_id'    => config("wechat.xcx_app_id"), // 小程序 APPID
            'mch_id'        => config("wechat.mch_id"),
            'key'           => config("wechat.key"),
            'notify_url'    => '',
            'cert_client'   => config("wechat.cert_client"), // optional，退款等情况时用到
            'cert_key'      => config("wechat.cert_key"),// optional，退款等情况时用到
            'log' => [ // optional
                'file' => './logs/wechat.log',
                'level' => 'debug'
            ],
            'mode' => 'dev', // optional, dev/hk;当为 `hk` 时，为香港 gateway。
        ];
    }
    public function wxPay($sn,$total,$openid,$body)
    {
        $order = [
            'out_trade_no'  => $sn,
            'total_fee'     => $total*100, // **单位：分**
            'body'          => $body,
            'spbill_create_ip' => '8.8.8.8',
            'openid'        => $openid,
        ];

        $notify = new Notify();
        $notify->send = json_encode(array_merge($this->config,$order));
        $notify->sn = $sn;
        $notify->save();
        $pay = new Pay(["wechat"=>$this->config]);
        return $pay->driver('wechat')->gateway('mp')->pay($order);
    }

    public function notify(Request $request)
    {
        $pay = new Pay(["wechat"=>$this->config]);
        $verify = $pay->driver('wechat')->gateway('mp')->verify($request->getContent());
        if ($verify) {
            return $verify;
        } else {
            return false;
        }
    }


    public function wxUserinfo() {
        $code = Input::get('code');
        $state = Input::get('state');
        //换成自己的接口信息
        $appid = $this->config["app_id"];
        $appsecret = $this->config["secret"];
        if (empty($code)) return ["code"=>500,"msg"=>"授权失败"];
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        $token = json_decode($this->httpGet($token_url));

        //$token = json_decode(file_get_contents($token_url));
        if (isset($token->errcode))  return ["code"=>500,"msg"=>"错误:".$token->errcode.",错误信息:".$token->errmsg.""];
        $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
        //转成对象
        $access_token = json_decode($this->httpGet($access_token_url));
        if (isset($access_token->errcode)) return ["code"=>500,"msg"=>"错误:".$access_token->errcode.",错误信息:".$access_token->errmsg.""];
        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
        //转成对象
        $user_info = json_decode($this->httpGet($user_info_url));
        if (isset($user_info->errcode)) return ["code"=>500,"msg"=>"错误:".$user_info->errcode.",错误信息:".$user_info->errmsg.""];
        return ["code"=>200,"data"=>$user_info];
    }

    public function userinfo() {
        // return (object)["openid"=>123];
        $code = request('code', '');
        //encryptedData 和 iv 在小程序端使用 wx.getUserInfo 获取
        $encryptedData = request('encryptedData', '');
        $iv = request('iv', '');
        $wxxcx = new Wxxcx();
        $userInfo = $wxxcx->getLoginInfo($code);
        //获取解密后的用户信息
        /**
         * {
        "openId": "xxxx",
        "nickName": "晚黎",
        "gender": 1,
        "language": "zh_CN",
        "city": "",
        "province": "Shanghai",
        "country": "CN",
        "avatarUrl": "http://wx.qlogo.cn/mmopen/xxxx",
        "watermark": {
        "timestamp": 1495867603,
        "appid": "your appid"
        }
        }
         */
        $user_info = $wxxcx->getUserInfo($encryptedData, $iv);
        return json_decode($user_info);
    }


    protected function httpGet($url) {
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $temp = curl_exec($ch);
        return $temp;


    }

    private function mkFile($dir_type,$content) {
        $file = fopen($dir_type, "w");
        if(empty($file)) return false;
        fwrite($file, $content);
        fclose($file);
        return true;
    }



    /**
     * 将xml转为array
     * @param string $xml
     * @throws WxPayException
     */
    public function Init($xml){

        $fromxml = $this->FromXml($xml);
        if($fromxml['return_code'] != 'SUCCESS'){

            return $fromxml;
        }
        //验证签名
        $sign = $this->MakeSign($fromxml);

        if($sign != $fromxml['sign']){
            return "签名错误";
        }
        return $fromxml;
    }

    /**
     * 将xml转为array
     * @param string $xml
     * @throws WxPayException
     */
    public function FromXml($xml){
        if(!$xml){
            return "xml数据异常！";
        }

        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $aa = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        return $aa;
    }

    /**
     * 生成签名
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    function MakeSign($input){
        //签名步骤一：按字典序排序参数
        ksort($input);
        $string = $this->ToUrlParams($input);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key="."GWERQ123123R12379A8SDQ12QWE12RG2";
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }



    /**
     * 格式化参数格式化成url参数
     */
    function ToUrlParams($array){
        $buff = "";
        foreach ($array as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    public function sendSuccess() {
        $su = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        echo $su;
        exit;
    }

}
